package com.ruoyi.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.security.utils.DictUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.domain.SysDictDataDraft;
import com.ruoyi.system.domain.SysDictDataFetcher;
import com.ruoyi.system.domain.SysDictDataTable;
import com.ruoyi.system.domain.dto.SysDictDataCacheDTO;
import com.ruoyi.system.domain.dto.SysDictDataPageInput;
import com.ruoyi.system.domain.dto.SysDictDataSaveInput;
import com.ruoyi.system.domain.dto.SysDictDataUpdateInput;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.babyfish.jimmer.sql.JSqlClient;
import org.babyfish.jimmer.sql.ast.mutation.SaveMode;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 字典 业务层处理
 *
 * @author ruoyi
 */

@Service
@RequiredArgsConstructor
public class SysDictDataServiceImpl implements ISysDictDataService {
//    @Autowired
//    private SysDictDataMapper dictDataMapper;

    private final JSqlClient sqlClient;

    /**
     * 根据条件分页查询字典数据
     *
     * @param input 字典数据信息
     * @return 字典数据集合信息
     */

    @Override
    public List<SysDictData> selectDictDataList(SysDictDataPageInput input) {
        SysDictDataTable dataTable = SysDictDataTable.$;
        return sqlClient.createQuery(dataTable)
                .whereIf(StrUtil.isNotEmpty(input.getDictType()), () -> dataTable.dictType().eq(input.getDictType()))
                .whereIf(StrUtil.isNotEmpty(input.getStatus()), () -> dataTable.status().eq(input.getStatus()))
                .whereIf(StrUtil.isNotEmpty(input.getDictLabel()), () -> dataTable.dictLabel().ilike(input.getDictLabel()))
                .select(dataTable.fetch(SysDictDataFetcher.$.allScalarFields()))
                .execute();
//        return dictDataMapper.selectDictDataList(dictData);
    }

    /**
     * 根据字典类型和字典键值查询字典数据信息
     *
     * @param dictType  字典类型
     * @param dictValue 字典键值
     * @return 字典标签
     */
    @Override
    public String selectDictLabel(String dictType, String dictValue) {
        SysDictDataTable dataTable = SysDictDataTable.$;
        return sqlClient.createQuery(dataTable)
                .where(dataTable.dictType().eq(dictType), dataTable.dictValue().eq(dictValue))
                .select(dataTable.fetch(SysDictDataFetcher.$.dictLabel()))
                .fetchOne().dictLabel();
//        return dictDataMapper.selectDictLabel(dictType, dictValue);
    }


    /**
     * 根据字典数据ID查询信息
     *
     * @param dictCode 字典数据ID
     * @return 字典数据
     */
    @Override
    public SysDictData selectDictDataById(Long dictCode) {
        return sqlClient.findById(SysDictData.class, dictCode);
    }

    /**
     * 批量删除字典数据信息
     *
     * @param dictCodes 需要删除的字典数据ID
     */
    @Override
    public void deleteDictDataByIds(Long[] dictCodes) {
        SysDictDataTable dataTable = SysDictDataTable.$;
        for (Long dictCode : dictCodes) {
            SysDictData data = selectDictDataById(dictCode);
            sqlClient.deleteById(SysDictData.class, dictCode);
            List<SysDictDataCacheDTO> dictDatas = sqlClient.createQuery(dataTable)
                    .where(dataTable.dictType().eq(data.dictType()))
                    .select(dataTable.fetch(SysDictDataCacheDTO.class))
                    .execute();
            DictUtils.setDictCache(data.dictType(), dictDatas);
        }
    }


    /**
     * 新增保存字典数据信息
     *
     * @param data 字典数据信息
     * @return 结果
     */
    @Override
    public int insertDictData(SysDictDataSaveInput data) {
        SysDictDataTable dataTable = SysDictDataTable.$;
        SysDictData sysDictData = SysDictDataDraft.$
                .produce(data.toEntity(), draft -> draft.applyCreateBy(user -> user.setUserId(SecurityUtils.getUserId())));
        int row = sqlClient.saveCommand(sysDictData).setMode(SaveMode.INSERT_ONLY).execute().getTotalAffectedRowCount();
        if (row > 0) {
            List<SysDictDataCacheDTO> dictDatas = sqlClient.createQuery(dataTable)
                    .where(dataTable.dictType().eq(data.getDictType()))
                    .select(dataTable.fetch(SysDictDataCacheDTO.class))
                    .execute();
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
        return row;
    }

    /**
     * 修改保存字典数据信息
     *
     * @param data 字典数据信息
     * @return 结果
     */
    @Override
    public int updateDictData(SysDictDataUpdateInput data) {
        SysDictDataTable dataTable = SysDictDataTable.$;
        SysDictData sysDictData = SysDictDataDraft.$
                .produce(data.toEntity(), draft -> draft.applyUpdateBy(user -> user.setUserId(SecurityUtils.getUserId())));
        int row = sqlClient.saveCommand(sysDictData).setMode(SaveMode.UPDATE_ONLY).execute().getTotalAffectedRowCount();
        if (row > 0) {
            List<SysDictDataCacheDTO> dictDatas = sqlClient.createQuery(dataTable).select(dataTable.fetch(SysDictDataCacheDTO.class)).execute();
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
        return row;
    }
}
